package cn.fbs.util.imageshort;


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.tomcat.util.codec.binary.Base64;

/**
 * @program: BQ
 * @description: 文件内容转换
 * @author: 张丽婧
 * @create: 2020-12-10 14:30
 **/
public class FileUtil {

    public static String getCompressBase64FromUrl(File file, int size) throws IOException {
        BufferedImage img = ImageIO.read(file);
        int width = img.getWidth();
        int height = img.getHeight();

        BufferedImage tag = new BufferedImage(width / size, height / size, BufferedImage.TYPE_INT_RGB);
        // Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的优先级比速度高 生成的图片质量比较好 但速度慢
        tag.getGraphics()
                .drawImage(img.getScaledInstance(width / size, -1, Image.SCALE_SMOOTH), 0, 0, null);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(tag, "jpeg", baos); // 这里也可以传 FileOutputStream 写进文件里
        String base64 = new String(Base64.encodeBase64(baos.toByteArray()));
        baos.close();
        return "data:image/png;base64," + base64;


    }

    public static void getCompressBase64FromUrl2(File file, int size, String pngPath) throws IOException {
        BufferedImage img = ImageIO.read(file);
        int width = img.getWidth();
        int height = img.getHeight();

        BufferedImage tag = new BufferedImage(width / size, height / size, BufferedImage.TYPE_INT_RGB);
        // Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的优先级比速度高 生成的图片质量比较好 但速度慢
        tag.getGraphics()
                .drawImage(img.getScaledInstance(width / size, -1, Image.SCALE_SMOOTH), 0, 0, null);
        FileOutputStream fileOutputStream = new FileOutputStream(pngPath);
        ImageIO.write(tag, "jpeg", fileOutputStream); // 这里也可以传 FileOutputStream 写进文件里
        fileOutputStream.close();

    }

    public static String getCompressBase64FromUrl(BufferedImage img, int size) throws Exception {
//        BufferedImage img = ImageIO.read(new File(url));
        int width = img.getWidth();
        int height = img.getHeight();

        BufferedImage tag = new BufferedImage(width / size, height / size, BufferedImage.TYPE_INT_RGB);
        // Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的优先级比速度高 生成的图片质量比较好 但速度慢
        tag.getGraphics()
                .drawImage(img.getScaledInstance(width / size, -1, Image.SCALE_SMOOTH), 0, 0, null);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(tag, "jpeg", baos); // 这
        // 里也可以传 FileOutputStream 写进文件里
    /*
    为什么有时候自动带头，有时候不带
     */

        String base64 = new String(Base64.encodeBase64(baos.toByteArray()));
        baos.close();
        return "data:image/png;base64," + base64;
    }
}
